﻿using Microsoft.Phone.Controls;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Windows8Accelerator.Core.Xaml.Helpers;

namespace Windows8Accelerator.Core.Xaml.Controls
{
    public class InternalGridView : Panorama, ISuperGroupStyleSelectorOwner
    {
        public GroupStyleSelector GroupStyleSelector
        {
            get { return (GroupStyleSelector)GetValue(GroupStyleSelectorProperty); }
            set { SetValue(GroupStyleSelectorProperty, value); }
        }
        public static readonly DependencyProperty GroupStyleSelectorProperty =
            DependencyProperty.Register("GroupStyleSelector", typeof(GroupStyleSelector), typeof(InternalGridView), new PropertyMetadata(null));

        private ObservableCollection<GroupItem> _GroupItems = new ObservableCollection<GroupItem>();

        public InternalGridView()
        {
            GroupStyleSelector = new SuperGroupStyleSelector(this);
            ItemsSource = _GroupItems;
        }       

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            var parent = this.GetParentOf<SuperListView>();
            if (parent != null)
            {
                var columnAndRowSpan = parent.GetItemColumnAndRowSpanSelector(item);
                //element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, columnAndRowSpan.Item1);
                //element.SetValue(VariableSizedWrapGrid.RowSpanProperty, columnAndRowSpan.Item2);
            }
            
            base.PrepareContainerForItemOverride(element, item);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (DefaultGroupStyle != null)
            {
                var superListView = this.GetParentOf<SuperListView>();
                if (DefaultGroupStyle.Panel != superListView.DynamicGroupedItemsPanelTemplate)
                    DefaultGroupStyle.Panel = superListView.DynamicGroupedItemsPanelTemplate;
                superListView.PropertyChanged += superListView_PropertyChanged;
            }
        }

        void superListView_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            var superListView = (SuperListView)sender;
            if (e.PropertyName.Equals("DynamicGroupedItemsPanelTemplate"))
            {
                if (DefaultGroupStyle.Panel != superListView.DynamicGroupedItemsPanelTemplate)
                    DefaultGroupStyle.Panel = superListView.DynamicGroupedItemsPanelTemplate;
            }
        }

        public SuperGroupStyle DefaultGroupStyle
        {
            get { return (SuperGroupStyle)GetValue(DefaultGroupStyleProperty); }
            set 
            { 
                SetValue(DefaultGroupStyleProperty, value); 
            }
        }
        public static readonly DependencyProperty DefaultGroupStyleProperty =
            DependencyProperty.Register("DefaultGroupStyle", typeof(SuperGroupStyle), typeof(InternalGridView), new PropertyMetadata(null));


        public DataTemplate GroupHeaderTemplate
        {
            get { return (DataTemplate)GetValue(GroupHeaderTemplateProperty); }
            set { SetValue(GroupHeaderTemplateProperty, value); }
        }
        public static readonly DependencyProperty GroupHeaderTemplateProperty =
            DependencyProperty.Register("GroupHeaderTemplate", typeof(DataTemplate), typeof(InternalGridView), new PropertyMetadata(null));

        public object ItemsSource1
        {
            get { return (object)GetValue(ItemsSource1Property); }
            set { SetValue(ItemsSource1Property, value); }
        }
        public static readonly DependencyProperty ItemsSource1Property =
            DependencyProperty.Register("ItemsSource1", typeof(object), typeof(InternalGridView), new PropertyMetadata(null, ItemsSource1PropertyChanged));

        private static void ItemsSource1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((InternalGridView)d).OnItemsSource1PropertyChanged(e);
        }

        private void OnItemsSource1PropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue is INotifyCollectionChanged)
            {
                ((INotifyCollectionChanged)e.OldValue).CollectionChanged -= InternalGridView_CollectionChanged;
            }
            if (e.NewValue is INotifyCollectionChanged)
            {
                ((INotifyCollectionChanged)e.NewValue).CollectionChanged += InternalGridView_CollectionChanged;
            }
            if (e.NewValue != null)
                InternalGridView_CollectionChanged(e.NewValue, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        void InternalGridView_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {            
            var list = sender as IEnumerable;

            if (string.IsNullOrEmpty(ItemsPath))
            {
                AddItemGroup(null, sender);
            }
            else
            {
                foreach (var item in list)
                {
                    AddItemGroup(item);
                }
            }
        }

        private void AddItemGroup(object group, object items = null)
        {
            if (group == null)
            {
                _GroupItems.Clear();
            }
            else if (_GroupItems.Any((g) => g.Item.Equals(group)))
            {
                return;
            }

            var groupItem = new GroupItem()
            {
                Item = group,
                ItemTemplate = ItemTemplate1,
            };
            BindingOperations.SetBinding(
                groupItem,
                GroupItem.ItemTemplateProperty,
                new Binding("ItemTemplate1") { Source = this });
            BindingOperations.SetBinding(
                groupItem,
                GroupItem.ItemTemplateSelectorProperty,
                new Binding("ItemTemplateSelector") { Source = this });
            BindingOperations.SetBinding(
                groupItem,
                GroupItem.ItemsProperty,
                new Binding(ItemsPath) { Source = group ?? items });
            _GroupItems.Add(groupItem);
        }

        public DataTemplate ItemTemplate1
        {
            get { return (DataTemplate)GetValue(ItemTemplate1Property); }
            set { SetValue(ItemTemplate1Property, value); }
        }
        public static readonly DependencyProperty ItemTemplate1Property =
            DependencyProperty.Register("ItemTemplate1", typeof(DataTemplate), typeof(InternalGridView), new PropertyMetadata(null));

        public string ItemsPath
        {
            get { return (string)GetValue(ItemsPathProperty); }
            set { SetValue(ItemsPathProperty, value); }
        }
        public static readonly DependencyProperty ItemsPathProperty =
            DependencyProperty.Register("ItemsPath", typeof(string), typeof(InternalGridView), new PropertyMetadata(""));

        public DataTemplateSelector ItemTemplateSelector
        {
            get { return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty); }
            set { SetValue(ItemTemplateSelectorProperty, value); }
        }
        public static readonly DependencyProperty ItemTemplateSelectorProperty =
            DependencyProperty.Register("ItemTemplateSelector", typeof(DataTemplateSelector), typeof(InternalGridView), new PropertyMetadata(null));

        public ICommand GroupHeaderClickCommand
        {
            get { return (ICommand)GetValue(GroupHeaderClickProperty); }
            set { SetValue(GroupHeaderClickProperty, value); }
        }
        public static readonly DependencyProperty GroupHeaderClickProperty =
            DependencyProperty.Register("GroupHeaderClickCommand", typeof(ICommand), typeof(InternalGridView), new PropertyMetadata(null));
    }
}
